package com.wjw.rest;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wjw.entity.User;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.ArrayList;
import java.util.List;

/**
 * 使用jersey框架发布rest风格的webservice接口
 * 1.引入相关jar包
 * 2.在web.xml中进行相关配置
 * 3.请求文档地址： http://localhost:8090/rest/application.wadl
 */
@Path("/user")
public class UserServlet {
    ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 用户列表：GET
     * http://127.0.0.1:8090/rest/user/list
     * @return
     * @throws JsonProcessingException
     */
    @GET
    @Path("/list")
    @Produces({MediaType.APPLICATION_JSON})
    public String list() throws JsonProcessingException {
        List<User> userList = new ArrayList<>();
        userList.add(new User(1,"吴佳威","123"));
        userList.add(new User(2,"dw","123"));
        userList.add(new User(3,"wjh","123"));
        return objectMapper.writeValueAsString(userList);//List转为json
    }

    /**
     * 根据用户id获取用户信息：GET
     * http://127.0.0.1:8090/rest/user/1
     * @param id
     * @return
     * @throws Exception
     */
    @GET
    //@Path("/getUserById/{id}")
    @Path("/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public String  userById(@PathParam("id") String id) throws Exception {
        User user = new User(Integer.parseInt(id),"张三","123");
        return objectMapper.writeValueAsString(user);
    }

    /**
     * 新增：POST
     * 使用postman发起Post请求
     * http://127.0.0.1:8090/rest/user/add
     * Headers中：Content-Type     application/json
     * Body中：选择raw             {"username":"gyf","password":"123"}
     * @param json
     * @return
     * @throws Exception
     */
    @POST
    @Path("/add")
    @Consumes(MediaType.APPLICATION_JSON)//请求数据是json格式
    @Produces(MediaType.APPLICATION_JSON)//响应数据是json格式
    public String add2(String json) throws Exception {
        System.out.println(json);//{"username":"gyf","password":"123"}
        //json转对象
        User user = objectMapper.readValue(json,User.class);
        System.out.println(user);
        return "success!!!";
    }

    /**
     * 新增：POST
     * 使用postman发起Post请求
     * http://127.0.0.1:8090/rest/user/add/json
     * Headers中：Content-Type     application/json
     * Body中：选择raw             {"username":"gyf","password":"123"}
     * @param json
     * @return
     * @throws Exception
     */
//    @POST
//    @Path("/add/{json}")
//    @Consumes(MediaType.APPLICATION_JSON)//请求数据是json格式
//    @Produces(MediaType.APPLICATION_JSON)//响应数据是json格式
//    public String add(String json) throws Exception {
//        System.out.println(json);//{"username":"gyf","password":"123"}
//        //json转对象
//        User user = objectMapper.readValue(json,User.class);
//        System.out.println(user);
//        return "success";
//    }

}
